package com.penglecode.nio.buffer;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

public class ByteBufferTest {

	public static void fileCopy(String srcFileFullPath, String destFileFullPath){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		FileChannel inChannel = null, outChannel = null;
		try {
			fis = new FileInputStream(srcFileFullPath);
			fos = new FileOutputStream(destFileFullPath);
			inChannel = fis.getChannel();
			outChannel = fos.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024 * 4);
			int totalSize = 0;
			int readSize = 0;
			while((readSize = inChannel.read(buffer)) != -1){
				buffer.flip();
				outChannel.write(buffer);
				buffer.clear();
				totalSize += readSize;
			}
			System.out.println(totalSize);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			IOUtils.closeQuietly(inChannel);
			IOUtils.closeQuietly(fis);
			IOUtils.closeQuietly(outChannel);
			IOUtils.closeQuietly(fos);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(Charset.defaultCharset());
		fileCopy("d:\\ByteBufferTest.java", "d:\\ByteBufferTest_bak.java");
	}

}
